package com.ankang.service.impl;

import com.ankang.controller.ChannelProcessor;

import com.ankang.entity.ChannelLevel;
import com.ankang.mapper.ChannelLevelMapper;
import com.ankang.service.TobaccoGradeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 烟包出库并行调度服务
 * 功能：初始化5个通道处理器，启动并行线程，管理全系统生命周期
 */
//@Slf4j
@Service
//@Component
public class SmokeOutboundExecutor {

    private static final Logger log = LoggerFactory.getLogger(SmokeOutboundExecutor.class);

    public SmokeOutboundExecutor() {
        log.info("SmokeOutboundExecutor 构造方法执行");
    }

    // 替换线程池创建逻辑
    private final ExecutorService channelExecutor = Executors.newFixedThreadPool(5);

    // 线程池（核心线程数=5，每个线程对应一个通道，避免线程频繁创建销毁）
//    private final ExecutorService channelExecutor = Executors.newFixedThreadPool(5,
//            r -> new Thread(r, "Smoke-Channel-" + System.currentTimeMillis()));

    @Autowired
    private ChannelLevelMapper channelLevelMapper;

    // 通道处理器列表（存储5个通道的处理器实例）
    private List<ChannelProcessor> channelProcessors;

    @Autowired
    private TobaccoGradeService tobaccoGradeService;

    @Autowired
    private ApplicationContext applicationContext;


    /**
     * 系统启动时初始化（Spring自动调用）
     */
    @PostConstruct
    public void init() {
        try {
            log.info("==================== 烟包出库服务开始初始化 ====================");
            System.out.println("======= SmokeOutboundExecutor init() 被调用 ======="); // 强制打印
            // 1. 从数据库查询所有通道信息（1-5通道）
            List<ChannelLevel> channelLevels = channelLevelMapper.selectList(new QueryWrapper<ChannelLevel>().orderByAsc("channel_id"));
            if (channelLevels.size() != 5) {
                throw new IllegalStateException("数据库通道数量异常，需配置5个通道");
            }
            log.info("从数据库读取到{}个通道配置，开始初始化每个通道...", channelLevels.size());
//             2. 初始化每个通道的处理器
//            channelProcessors = channelLevels.stream()
//                    .map(ChannelProcessor::new)
//                    .toList();

            channelProcessors = channelLevels.stream()
                    .map(level -> {
                        // 从 Spring 容器获取 ChannelProcessor 实例
                        ChannelProcessor processor = applicationContext.getBean(ChannelProcessor.class);
                        processor.init(level); // 手动传入 ChannelLevel 并初始化
                        return processor;
                    })
                    .toList();

            // 3. 定义计数器，等待所有通道初始化完成（关键：初始化initLatch）
            CountDownLatch initLatch = new CountDownLatch(channelProcessors.size());

            // 4. 启动所有通道（并行执行，每个通道一个线程）
            channelProcessors.forEach(processor ->
                    channelExecutor.submit(() -> {
                        try {
                            Thread.currentThread().setName("Smoke-Channel-" + processor.getChannelId());
                            processor.startChannel();
                        } catch (Exception e) {
                            log.error("通道{} 启动异常", processor.getChannelId(), e);
                        }
                    })
            );
            // 5等待所有通道初始化（最长等待15秒，超过则强制继续）
            boolean allInitialized = initLatch.await(15, TimeUnit.SECONDS);
            if (!allInitialized) {
                log.warn("部分通道初始化超时！");
            }

            // 6、统一检查所有通道连接状态
            log.info("==================== 通道初始化结果汇总 ====================");
            for (ChannelProcessor processor : channelProcessors) {
                int channelId = processor.getChannelLevel().getChannelId();
                if (processor.isAllConnected()) {
                    log.info("通道{}：所有设备连接成功", channelId);
                } else {
                    log.error("通道{}：连接异常 - {}", channelId, processor.getConnectionErrorInfo());
                }
            }

            log.info("==================== 烟包出库服务初始化完成！5个通道已并行启动，等待烟包触发 ====================");
        } catch (Exception e) {
            log.error("==================== 烟包出库服务初始化失败！ ====================", e);
            throw new RuntimeException("系统启动异常", e);
        }
    }

    /**
     * 系统停止时释放资源（Spring自动调用）
     */
    @PreDestroy
    public void destroy() {
        log.info("==================== 烟包出库服务开始停止 ====================");
        // 1. 停止所有通道处理器
        if (channelProcessors != null) {
            channelProcessors.forEach(ChannelProcessor::stopChannel);
        }

        // 关闭线程池
        channelExecutor.shutdown();
        try {
            if (!channelExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
                channelExecutor.shutdownNow();
            }
        } catch (InterruptedException e) {
            channelExecutor.shutdownNow();
        }
        log.info("==================== 烟包出库服务停止完成 ====================");

    }
}
